Thread: Self referential class || Stroring an address of a class

  1. #1
    Registered User Sara th's Avatar
    Join Date
    Apr 2011
    Location
    India
    Posts
    10

    Question Self referential class || Stroring an address of a class

    Can we use a self referential class in C++? If yes what is the difference between self referencing in C and in C++

    Is there any problems in storing the address of classes?

    PS: I wrote a program using the concept in C++ but it isn't working. Reply asap

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    What do you mean by "self referential class"?

    There is no such thing as the address of a class. A class is a category of object. Objects have addresses in memory. Categories do not.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    Registered User Sara th's Avatar
    Join Date
    Apr 2011
    Location
    India
    Posts
    10
    Fine I meant the address of the objects!

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    So if you mean "can an object store its own address", then the answer is yes. In fact, you cannot stop an object from storing its own address, as that is what "this" represents.

  5. #5
    Registered User Sara th's Avatar
    Join Date
    Apr 2011
    Location
    India
    Posts
    10
    I want to make the objects linked

  6. #6
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Okay. There's not really anything stopping you from doing so. Use the & operator to get an address from an object.

    If there's some error with the code you've written, you can get actual advice and hints if you tell us (a) what you did (i.e. show us what you've written) and (b) what errors you are getting.

  7. #7
    Registered User Sara th's Avatar
    Join Date
    Apr 2011
    Location
    India
    Posts
    10
    Here is the code. The program is very simple, a book shop - in admin mode we need add books as in client mode we can subscribe them. I want to do this program using dynamic memory allocation not array of objects.


    Code:
    /*Sarath*/
    
    #include<iostream.h>
    #include<conio.h>
    
    class bookshop;
    
    bookshop *start,*temp,*ptr;
    
    class bookshop        //self referential class to define a bookshop
    {
    
    	char title[20];           //to store book title
    	char author[20];          //to store author name
    	float price;              //price of the book
    	int copies;               //no: of copies
    	public:
    	class bookshop *next;     //to point to node of same class
    
    	public:
    
    	bookshop(bookshop *);
    	void admin();              //to enter new stock
    	void client();             //to search and purchase
    	void display();            //to display book details
    
    };
    
    bookshop::bookshop(bookshop *temp)    //parametrised constructor
    {                                     //to insert new node
    	if(start==NULL)
    	{
    		start=temp;
    		start->next=NULL;
    	}
    	else
    	{
    
    		ptr=start;
    		while(ptr->next!=NULL)
    			ptr=ptr->next;
    		ptr->next=temp;
    		temp->next=NULL;
    	}
    }
    
    void main()
    {
    
    	int choice;
    	start=NULL;
    	clrscr();
    
    	do
    	{
    		cout<<"\n\n\tBook Shop\n";
    		cout<<"\n\t1. Admin\n\t2. Client\n\t3. Quit";
    		cout<<"\n\n\tChoice: ";
    		cin>>choice;
    
    		bookshop *temp=new bookshop(temp);
    		switch(choice)
    		{
    
    			case 1:
    				temp->admin();
    				break;
    			case 2:
    				temp->client();
    				delete temp;     //to delete last node
    				break;
    			case 3:
    				cout<<"\n\tPress any key to quit..";
    				break;
    			default:
    				cout<<"\nInvalid choice!\n";
    
    		}
    
    	}while(choice!=3);
    
    	getch();
    
    }
    
    void bookshop::admin()
    {
    	cout<<"\n\tBook title: ";
    	cin>>title;
    	cout<<"\n\tAuthor: ";
    	cin>>author;
    	cout<<"\n\tPrice: ";
    	cin>>price;
    	cout<<"\n\tNo of copiess: ";
    	cin>>copies;
    	display();
    }
    
    void bookshop::client()
    {
    	start->display();
    	int flag=0;
    	cout<<"\n\tTitle?:";
    	cin>>title;
    	cout<<start;
    	ptr=start;
    
    	while(ptr->next!=NULL)
    	{
    
    		if(ptr->title==title)
    		{
    
    			ptr->display();
    			flag=1;
    			break;
    
    		}
    		ptr=ptr->next;
    	}
    
    	if(flag==0)
    		cout<<"\n\n\t"<<title<<" is not available!";
    
    }
    
    void bookshop::display()
    {
    
    	cout<<"\n\n\t"<<title<<" is available";
    	cout<<"\n\tAuthor: "<<author;
    	cout<<"\n\tPrice: "<<price;
    	ptr=start;
    	while(ptr!=NULL)   {
    	cout<<" "<<ptr->title;          ptr=ptr->next;}
    
    }

  8. #8
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Your code is all over the place. Be careful with your global pointers, you are redeclaring local variables with the same name as your globals. Additionally:

    1. void main is wrong. Read how to define main - FAQ
    2. This is C++, not C. You should be using std::string vice char arrays.
    3. Again since this is c++, you should be using std::vector vice trying to implement a linked list.

    Letting us know what isn't working and the error messages you recieve is the way to get more specific help here.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  9. #9
    Registered User Sara th's Avatar
    Join Date
    Apr 2011
    Location
    India
    Posts
    10
    Whats wrong in main? Linking is working well[I have checked by printing the addresses of the objects] But the problem is that I cant access the members using the object pointer.

  10. #10
    Registered User Sara th's Avatar
    Join Date
    Apr 2011
    Location
    India
    Posts
    10
    No syntax errors. But when I print the values using "start->title" I am getting smileys and all

  11. #11
    Registered User
    Join Date
    Jan 2010
    Posts
    412
    For a minute there I thought I was in the C forum section..

    1) This isn't C++, it's "C with classes"
    2) Replace your compiler with a standard-compliant one. iostream.h is pre-standard and deprecated.
    3) Why are you rolling your own linked list? Use std::list
    4) Why does each bookshop only hold one book? I suggest a single class bookshop which can hold several class book, in for example an std::list or vector
    5) main is leaking memory. Look up RAII and smart pointers.
    6) "bookshop *temp=new bookshop(temp);" temp is uninitialized when passed to bookshop()

  12. #12
    Registered User Sara th's Avatar
    Join Date
    Apr 2011
    Location
    India
    Posts
    10
    I am not an expert in C/C++. Thats the answer for all the 'whys'. And thanks for the suggestions

  13. #13
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    733
    I really appreciate pointing out mistakes, but whenever a newcomer is asking for help, everyone is proposing already-made tools. That's great, but keep in mind that C/C++ is used for learning BASIS of programming. The fact that you have smart pointers, linked-lists, vectors, strings here does not mean that these will be present in every other language. Telling him to use std::list to solve the problem is not the way to go. Let him get his idea working first and then prove it is not a good solution.

    Yet you require from him distinguishing C from C++, while one is generally a superset of the other.

    About the leaking memory:
    The global pointer variable "start", which points to the first node, has to be deleted. The memory it points to has to be freed when it is no longer used. You might want to do this at the end of your main():

    Code:
    int main()
    {
        ...
        delete start; // we remove tree from memory
        return 0;
    }
    This will delete only the first node, since you pass to the delete operator only start. Nodes should be deleted recursively. You can do this implementing a destructor:

    Code:
    bookshop::~bookshop() // destructor
    {
    	if(next!=NULL) // if this is not the last node, delete the next one
    	{
    		delete next;
    	}
    }
    Your constructor does not need the 'temp' parameter. You do not need to pass the object's address to any of its method, since it is done automatically by the language. Remove this parameter and use 'this' pointer instead, which has the functionality you want.
    Last edited by kmdv; 08-08-2011 at 03:38 PM.

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by kmdv
    I really appreciate pointing out mistakes, but whenever a newcomer is asking for help, everyone is proposing already-made tools. That's great, but keep in mind that C/C++ is used for learning BASIS of programming. The fact that you have smart pointers, linked-lists, vectors, strings here does not mean that these will be present in every other language. Telling him to use std::list to solve the problem is not the way to go.
    I disagree. Computer science is not the only basis for programming; programmatic problem solving is another basis (now I feel like I'm talking linear algebra, but anyway...), and in this it makes sense to use the tools provided by C++. Sure, one should also learn how to implement these data structures, but this should be done as a separate exercise which comes with the teaching of how to utilise RAII. I suggest that you read Stroustrup's essay on Learning Standard C++ as a New Language (PDF) and Koenig and Moo's Accelerated C++ as an example of the general approach. (Sara th: you may want to consider working through Accelerated C++ yourself to get a good grounding in C++ and programming technique.)
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Registered User krishnapollu's Avatar
    Join Date
    Dec 2010
    Location
    KERALA
    Posts
    29
    @ sarath :
    I I just read thcode. I think ur problem is that u can't search for a particular book. The mistake is , u have used == operator to compare strings.. Instead u should use strcmp()..

    @others :
    try to understand what is the problem he is facing.. And make him clarify it rather than confusing him with much complex things.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Function or code to Determining class of IP address
    By hari_bly in forum C Programming
    Replies: 1
    Last Post: 06-10-2011, 01:59 AM
  2. how to return the address of a member of a class
    By *DEAD* in forum C++ Programming
    Replies: 6
    Last Post: 07-13-2007, 09:15 AM
  3. How do I make a class call it's own address
    By rakan in forum C++ Programming
    Replies: 3
    Last Post: 09-22-2006, 09:57 PM
  4. Address will always return true? (class vectors + member vars)
    By littleweseth in forum C++ Programming
    Replies: 12
    Last Post: 11-27-2003, 01:49 AM
  5. Address of a non-static class member function?
    By darksaidin in forum C++ Programming
    Replies: 8
    Last Post: 08-25-2003, 01:25 PM